package com.smbms.util;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

public class MybatisUtil {

    static SqlSessionFactory sqlSessionFactory;

    public static SqlSession getSqlSession() throws IOException {
        if(sqlSessionFactory == null) {
            //1.读取mybatis核心配置文件
            InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
            //2.创建sql会话工厂解析器
            SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
            //3.通过解析器，解析文件获取到sql会话工厂
            sqlSessionFactory = sqlSessionFactoryBuilder.build(inputStream);
        }
        //4.通过sql会话工厂获取到sql会话
        return  sqlSessionFactory.openSession();
    }
}
